/*
 * @Description:
 * @Author: maxyang
 * @Date: 2022-05-19 14:32:17
 * @LastEditTime: 2022-06-26 18:36:28
 * @LastEditors: liutq
 * @Reference:
 */
package announcement

import (
	"errors"
	"time"

	"github.com/maxyang107/jinglan/common"
	"github.com/maxyang107/jinglan/model"
)

type Announcement struct {
	ID         uint      `gorm:"column:id; parimary_key" json:"ID"`
	Title      string    `gorm:"column:title;" json:"Title" binding:"required"`
	Content    string    `gorm:"column:content;" json:"Content" binding:"required"`
	OrderKey   uint8     `gorm:"column:order_key;" json:"OrderKey"`
	CreateTime time.Time `gorm:"column:create_time;" json:"create_time"`
}

type AnnouncementList struct {
	Page    int
	PerPage int
	Total   int
	Data    []Announcement
}

func GetAnnouncementList(query_ common.AnnouncementList) AnnouncementList {
	var announcement AnnouncementList
	announcement.Page = query_.Page
	announcement.PerPage = query_.PerPage
	announcement.Total = getTotal(query_)
	model.Db.Model(&Announcement{}).Order("order_key desc").Order("id desc").Limit(query_.PerPage).Offset((query_.Page - 1) * query_.PerPage).Scan(&announcement.Data)
	return announcement
}

func getTotal(query_ common.AnnouncementList) int {

	var total int
	model.Db.Model(&Announcement{}).Count(&total)
	pageNum := total / query_.PerPage
	if total%query_.PerPage != 0 {
		pageNum++
	}
	return pageNum
}

//获取公告详情
func GetAnnouncementDetail(id_ uint) Announcement {
	var annDetail Announcement
	model.Db.Where(&Announcement{ID: id_}).First(&annDetail)
	return annDetail
}

/**
 * @description: 方法描述：发布公告
 * @Author: maxyang
 * @return {*}
 * @param {Announcement} param_
 */
func SaveAnnouncement(param_ Announcement) error {
	var tmp Announcement
	model.Db.Where(&Announcement{Title: param_.Title, Content: param_.Content}).First(&tmp)

	if tmp.ID > 0 {
		return errors.New("该公告内容已存在，请勿重复发布相同公告")
	}
	param_.CreateTime = time.Now()
	if err := model.Db.Create(&param_).Error; err != nil {
		return errors.New("公告发布失败")
	}
	return nil
}

/**
 * @description: 方法描述：修改公告
 * @Author: maxyang
 * @return {*}
 * @param {Announcement} param_
 */
func ModifyAnnouncement(param_ Announcement) error {
	var tmp Announcement
	model.Db.Where(&Announcement{ID: param_.ID}).First(&tmp)

	if tmp.ID == 0 {
		return errors.New("该公告内容不存在！")
	}

	model.Db.Model(&Announcement{}).Update(&param_)
	return nil
}
